﻿using Gp.Scripts.Core.Res;
using Gp.Scripts.Core.Unit;
using QFramework;
using UnityEngine;

namespace Gp.Scripts.Core {
    /// <summary>
    /// 游戏实体基类
    /// </summary>
    public abstract class BaseEntity : IEntityGo
    {
        public abstract string Guid { get; }
        public ConfigUnit EntityConfig { get; private set; }
        private ResLoader _resLoader = null;

        public ResLoader ResLoader => _resLoader ??= ResLoader.Allocate();


        public void Initialize(ConfigUnit config)
        {
            EntityConfig = config;
            OnInitialize();
        }

        protected virtual void OnInitialize() { }
        
        

        public void Destroy()
        {
            OnDestroy();
            _resLoader?.Recycle2Cache();
        }
        
        protected virtual void OnDestroy() { }
        
        public abstract bool ContainsTag(int tags);
        public abstract IntValue CurHealth { get; }
        public abstract IntValue MaxHealth { get; }
        public abstract void ReceiveDamage(int damage);
        public abstract void ReceiveCure(int cure);


        public virtual void ReceiveImpose(Vector3 force) { }

        public virtual void MarkHighlight() { }
        public virtual void MarkDeHighlight() { }
        /// <summary>
        /// 当被选中（鼠标点击）时调用
        /// </summary>
        public virtual void OnEntitySelect() { }


        #region Proxy
        public EntityBehaviour EntityBehaviour { get; set; }
        public Transform transform => EntityBehaviour.transform;
        public GameObject gameObject => EntityBehaviour.gameObject;
        
        public int GetInstanceID() => EntityBehaviour.GetInstanceID();
        public T GetComponent<T>() => EntityBehaviour.GetComponent<T>();
        public bool TryGetComponent<T>(out T component) where T : Component => EntityBehaviour.TryGetComponent(out component);

        public string tag
        {
            get => EntityBehaviour.tag;
            set => EntityBehaviour.tag = value;
        }

        public static bool operator true(BaseEntity entity)
        {
            return entity.IsEntityDestroyed();
        }

        public static bool operator false(BaseEntity entity)
        {
            return !entity.IsEntityDestroyed();
        }

        public static bool operator !(BaseEntity entity)
        {
            return !entity.IsEntityDestroyed();
        }
        #endregion
    }

    public static class GameEntityExtensions
    {
        public static bool IsEntityDestroyed(this BaseEntity entity)
        {
            return entity != null && entity.EntityBehaviour != null;
        }
    }
}